<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>菜单和权限管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../../lib/layui-v2.5.5/css/layui.css" media="all">
	  <link rel="stylesheet" href="../../../lib/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
    <link rel="stylesheet" href="../../../css/public.css" media="all">
</head>

<body>
<div class="layuimini-container">
    <div class="layuimini-main">
		<!--搜索开始-->
        <fieldset class="layui-elem-field layuimini-search">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="" id="searchFrm">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">关键字</label>
                            <div class="layui-input-inline">
                                <input type="text" name="title" id="search_title" autocomplete="off" class="layui-input">
                            </div>
                        </div>
						<div class="layui-inline">
						   <a class="layui-btn"  id="data-search-btn"><label class="layui-icon layui-icon-search"></label>搜索</a>
						   	<a class="layui-btn layui-btn-warm" onclick="javascript:$('#searchFrm')[0].reset()" lay-filter="data-search-btn"><label class="layui-icon layui-icon-refresh"></label>重置</a>
						</div>
					</div>
                </form>
            </div>
        </fieldset>
		<!--搜索结束-->
		<!--表格开始-->
		<a class="layui-btn  menu_btn_add " href="javascript:void(0)" id="addMenuBtn"> 
		<span class="layui-icon layui-icon-add-1"></span> 添加
		</a>
        <table class="layui-hide" id="menuTable" lay-filter="menuTable"></table>
		<div style="display: none;" id="menuTableBar" >
			<a class="layui-btn menu_btn_update layui-btn-xs layui-btn-warm data-count-delete" lay-event="update">修改</a>
		    <a class="layui-btn menu_btn_delete layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
		</div>
		
		<script type="text/html" id="spreadTpl">
		  <!-- 这里的 checked 的状态只是演示 -->
		  <input type="checkbox" name="spread" value="{{d.id}}" lay-skin="switch" lay-text="展开|不展开" lay-filter="spreadSwitch" {{ d.spread == 1 ? 'checked' : '' }}>
		</script>
		<script type="text/html" id="availableTpl">
		  <!-- 这里的 checked 的状态只是演示 -->
		  <input type="checkbox" name="available" value="{{d.id}}" lay-skin="switch" lay-text="可用|不可用" lay-filter="availableSwitch" {{ d.available == 1 ? 'checked' : '' }}>
		</script>
		
		<!--表格结束-->
		
		<!--添加和修改的弹出层开始-->
		<div id="addOrUpdateDiv" style="display: none;padding: 0.3125rem">
			<form method="post" class="layui-form layui-form-pane" lay-filter="dataFrm" id="dataFrm">
				<div class="layui-form-item" id="div_pid">
						<label class="layui-form-label">菜单类型</label>
						<div class="layui-input-block">
							  <input type="radio" name="type" lay-filter="typeFilter" value="topmenu" title="顶部菜单" >
							  <input type="radio" name="type" lay-filter="typeFilter" value="leftmenu" title="左侧菜单" checked="">
							  <input type="radio" name="type" lay-filter="typeFilter" value="permission" title="按钮权限" >
						</div>
				 </div>
				<div class="layui-form-item item_leftmenu item_permission">
						<label class="layui-form-label">父级菜单</label>
						<div class="layui-input-inline">
							<!-- // 父菜单id -->
						   <input type="hidden" name="pid" id="p_id" />
						   <!-- // 显示菜单名称 -->
						   <input type="text" name="pid_name" id="p_name" readonly="readonly" autocomplete="off" placeholder="请选择父级菜单和权限" class="layui-input">
						</div>
						<!-- // 按钮触发 -->
						<div class="layui-input-inline">
						   <a class="layui-btn layui-btn-warm" id="doSelectMenu"><label class="layui-icon layui-icon-male"></label>选择</a>
						</div>
				 </div>
				 <div class="layui-form-item ">
					<label class="layui-form-label">名称</label>
					<div class="layui-input-block">
					   <input type="hidden" name="id" />
					  <input type="text" name="title" lay-verify="required" autocomplete="off" placeholder="请输入菜单和权限名称" class="layui-input">
					</div>
				  </div>
				  <div class="layui-form-item">
					<label class="layui-form-label">编码</label>
					<div class="layui-input-block">
					  <input type="text" name="typecode" id="typecodes"  autocomplete="off" placeholder="请输入菜单或权限编码" class="layui-input">
					</div>
				   </div>
				   <div class="layui-form-item item_topmenu item_permission  item_leftmenu">
						<label class="layui-form-label">图标</label>
						<div class="layui-input-block">
							 <input type="text" id="iconPicker"  value="" name="icon"  autocomplete="off" placeholder="选择图标" class="layui-input" lay-filter="iconPicker" style="display:none;">
						</div>
				    </div>
					<div class="layui-form-item  item_leftmenu">
							<label class="layui-form-label">链接地址</label>
							<div class="layui-input-block">
							  <input type="text" name="href"  autocomplete="off" placeholder="请输入菜单和权限地址" class="layui-input">
							</div>
					 </div>
					<div class="layui-form-item item_leftmenu">
							<label class="layui-form-label">TARGET</label>
							<div class="layui-input-block">
									<input type="radio" name="target" value="_self" title="_self" checked="" >
									<input type="radio" name="target" value="_blank" title="_blank" >
							</div>
					 </div>
					  <div class="layui-form-item">
					  		<label class="layui-form-label">排序码</label>
					  		<div class="layui-input-block">
					  		  <input type="text" name="ordernum" id="ordernum"  readonly="readonly" lay-verify="required"  autocomplete="off" placeholder="请输入排序码" class="layui-input">
					  		</div>
					   </div>
				  <div class="layui-form-item">
						<div class="layui-input-block" style="text-align: center;">
							<a class="layui-btn " lay-submit=""  lay-filter="doSubmit"><label class="layui-icon layui-icon-release"></label>提交</a>
							<a class="layui-btn layui-btn-warm" onclick="javascript:$('#dataFrm')[0].reset()" lay-filter="data-search-btn"><label class="layui-icon layui-icon-refresh"></label>重置</a>
						</div>
				   </div>
			</form>
		</div>
		<!--添加和修改的弹出层结束-->
    </div>
</div>
<script src="../../../lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="../../../lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
<script src="../../../js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script src="../../../lib/jq-module/jquery.particleground.min.js" charset="utf-8"></script>
<script src="../../../lib/common/jquery.cookie.min.js" charset="utf-8"></script>
<script src="../../../lib/common/common.js" charset="utf-8"></script>
<script src="../../../lib/common/selectLayer.js" charset="utf-8"></script>


<script>
    layui.use(['form', 'table','layer','treeTable','laydate','iconPickerFa'], function () {
        var form = layui.form;
		var table = layui.table;
		var layer=layui.layer;
		var laydate=layui.laydate;
		  var iconPicker = layui.iconPickerFa;
		var treeTable = layui.treeTable;
		
		
		// 图标选择器
		iconPicker.render({
		    // 选择器，推荐使用input
            elem: '#iconPicker',
            // fa 图标接口
            url: "../../../lib/font-awesome-4.7.0/less/variables.less",
            // 是否开启搜索：true/false，默认true
            search: true,
            // 是否开启分页：true/false，默认true	
            page: true,
            // 每页显示数量，默认12
            limit: 16,
			/*  // 点击回调
            click: function (data) {
                // console.log(data);
            },
            // 渲染成功后的回调
            success: function (d) {
                // console.log(d);
            } */
		}); 
		
		//缓存当前操作的是哪个表格的哪个tr的哪个td
		$(document).off('mousedown', '.layui-table-grid-down').on('mousedown', '.layui-table-grid-down', function(event) {
			//直接记录td的jquery对象
			table._tableTrCurrr = $(this).closest('td');
		});
		
		//给弹出的详情里面的按钮添加监听级联的触发原始table的按钮的点击事件
		$(document).off('click', '.layui-table-tips-main [lay-event]').on('click', '.layui-table-tips-main [lay-event]',
			function(event) {
				var elem = $(this);
				var tableTrCurrr = table._tableTrCurrr;
				if (!tableTrCurrr) {
					return;
				}
				var layerIndex = elem.closest('.layui-table-tips').attr('times');
				layer.close(layerIndex);
				table._tableTrCurrr.find('[lay-event="' + elem.attr('lay-event') + '"]').first().click();
			});
			
        var tableIns=treeTable.render({
			tree: {
				iconIndex: 1,  // 折叠图标显示在第几列
				idName: 'id',  // 自定义id字段的名称
				pidName: 'pid',  // 自定义标识是否还有子节点的字段名称
				isPidData: true  ,// 是否是pid形式数据
				openName: 'spread',  // 自定义默认展开的字段名
				arrowType: 'arrow2',   // 自定义箭头风格
				        getIcon: function(d) {  // 自定义图标
				            // d是当前行的数据
							
							if(d.pid == 0){
								return '<i class="ew-tree-icon ew-tree-icon-folder"></i>';
							}else{
								 return '<i class="ew-tree-icon ew-tree-icon-file"></i>';
							}
							
				            // if (d.haveChild) {  // 判断是否有子集
				            //     return '<i class="ew-tree-icon ew-tree-icon-folder"></i>';
				            // } else {
				            //     return '<i class="ew-tree-icon ew-tree-icon-file"></i>';
				            // }
				        }
			 },
            elem: '#menuTable',
			cellMinWidth:true,
            cols: [
                {type: "numbers"},
                {field: 'title',  title: '菜单或权限名称',width: 230},
                {field: 'id', title: 'ID', align: "center"},
            	{field: 'pid', title: 'PID', align: "center"},
                {field: 'type', title: '类型', align: "center",templet:function(d){
            		if (d.type == 'topmenu') {
            				return '<span class="layui-badge layui-bg-gray">顶部菜单</span>';
            			}
            				if (d.type == 'leftmenu') {
            					return '<span class="layui-badge layui-bg-blue">左侧菜单</span>';
            			} else {
            					return '<span class="layui-badge layui-bg-molv">权限</span>';
            			}
            		}
            	},
                {field: 'href',  title: '地址', align: "center",width: 180},
                {field: 'typecode',  title: '编码', align: "center",width: 120},
                {field: 'icon',  title: '图标', align: "center",width: 120,templet:function(d){
            		var x="<i class='"+d.icon+"' style='width:15px;height:15px;'></i>";
            		return x;
            	}},
            	{field: 'target',  title: 'TARGET', align: "center",width: 100},
            	{field: 'ordernum',  title: '排序码', align: "center",width: 80},
            	{field: 'spread',  title: '是否展开', align: "center",width: 120,templet:'#spreadTpl'},
            	{field: 'available',  title: '是否可用', align: "center",width: 120,templet:'#availableTpl'},
                {title: '操作', templet: '#menuTableBar',width: 120, fixed: "right", align: "center"}
            ],
			 reqData: function(data, callback) {
				 if(data==undefined){
					 // 在这里写ajax请求，通过callback方法回调数据
					 $.get(api+'menu/loadAllMenu', function (res) {
					 	callback(res.data);  // 参数是数组类型
					 });
				 }else{
					callback([]);  //回调一个空数据去渲染表格 
				 }
				
			}
        });

			    


        // 监听搜索操作
		$("#data-search-btn").on("click",function(){
			var title=$("#search_title").val();
			if(title){
				tableIns.filterData(title);
			}else{
				tableIns.reload();
			}
		});
		//监听表单元素的事件
		 //监听展开操作
		  form.on('switch(spreadSwitch)', function(obj){
			$.post(api+"menu/updateMenu",{id:this.value,spread:obj.elem.checked?1:0},function(res){
				layer.msg(res.msg);
				tableIns.reload();
			})
		    layer.tips(this.value + ' ' + this.name + '：'+ obj.elem.checked, obj.othis);
		  });
		  
		  
		  //监听可用操作
	     form.on('switch(availableSwitch)', function(obj){
		  $.post(api+"menu/updateMenu",{id:this.value,available:obj.elem.checked?1:0},function(res){
		  	layer.msg(res.msg);
			tableIns.reload();
		  })
	     });
		 
		 

		//监听添加按钮的事件
		$("#addMenuBtn").click(function(){
			openAddmenu(); //打开添加的弹出层
		})
		
		// 监听单选按钮的点击操作
		form.on('radio(typeFilter)', function(data){
		  console.log(data.value); //被点击的radio的value值
		  $(".item_topmenu").show();
		  $(".item_leftmenu").show();
		  $(".item_permission").show();
		  if(data.value=='topmenu'){
			   $(".item_leftmenu").hide();
			   $(".item_permission").hide();
			   $(".item_topmenu").show();
		  }else if(data.value=='leftmenu'){
			  $(".item_permission").hide();
			  $(".item_topmenu").hide();
			  $(".item_leftmenu").show();
		  }else{
			  $(".item_leftmenu").hide();
			  $(".item_topmenu").hide();
			  $(".item_permission").show();
		  }
		});  
		
		//监听行数据的事件
        treeTable.on('tool(menuTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'delete') {
				
				layer.prompt({
					formType: 1,
					value: '',
					maxlength: 6, //可输入文本的最大长度，默认500
					title: '正在删除"'+data.title+'"敏感操作，请输入口令，防止杂毛',
				}, function(value, index, elem) {
					if (value == 'yby123') {
						layer.load(0, {time: 1500});
						// 查询是否有子菜单
						$.get(api+"menu/getMenuChildrenCountById",{id:data.id},function(res1){
							// 如果pid = x 有子部门则违反逻辑
							if(res1.data>0){
								layer.msg("当前菜单和权限有子菜单和权限，请选择删除子菜单和权限");
								layer.close(index);
							}else{
								// 进行删除菜单
								$.post(api+"menu/deleteMenu",{id:data.id},function(res){
									layer.msg(res.msg);
									obj.del();
									layer.close(index);
								})
							}
						})
					} else {
						layer.msg("口令错误");
					}
				});
				
				
            }else if(obj.event === 'update'){
				openUpdatemenu(data);
		    }
        });
		
		//打开添加公告的弹层
		var mainIndex;
		var url;  //动态的url
		function openAddmenu(){
			mainIndex=layer.open({
				type:1,
				title:'添加菜单和权限',
				content:$("#addOrUpdateDiv"),
				area:['800px','600px'],
				success:function(index){
					layer.tips('菜单或权限标识  如：system|business|query:add', '#typecodes',{
						tips: 1
					});
					
					
					// url
					url=api+"menu/addMenu";
					
					//重置表单
					$("#dataFrm")[0].reset();
					
					//加载最大的排序码
					$.get(api+"menu/queryMenuMaxOrderNum",function(res){
						$("#ordernum").val(res.data);
					})
					// 权限隐藏
					$(".item_permission").hide();
					// 头部菜单隐藏
					$(".item_topmenu").hide();
					// 左菜单显示
					$(".item_leftmenu").show();
				}
			});	
		}
		function openUpdatemenu(data){
			mainIndex=layer.open({
				type:1,
				title:'修改['+data.title+']菜单和权限',
				content:$("#addOrUpdateDiv"),
				area:['800px','600px'],
				success:function(index){
					
					url=api+"menu/updateMenu";
					//装载数据表格
					form.val("dataFrm",data);
					
					// 根据菜单id查询 信息 
					$.get(api+"menu/getMenuById",{id:data.pid},function(res){
						console.log(res);
						if(res.data != null){
							$("#p_name").val(res.data.title);
						}
					});
					
					
					// 当点击修改 时判断 该类型  显示 对应的 表单信息
					if(data.type=='topmenu'){
					   $(".item_leftmenu").hide();
					   $(".item_permission").hide();
					   $(".item_topmenu").show();
					}else if(data.type=='leftmenu'){
					  $(".item_permission").hide();
					  $(".item_topmenu").hide();
					  $(".item_leftmenu").show();
					}else{
					  $(".item_leftmenu").hide();
					  $(".item_topmenu").hide();
					  $(".item_permission").show();
					}
				}
			});	
		}
		//提交数据
		form.on("submit(doSubmit)",function(data){
			layer.load(0, {time: 1500});
			var params= $("#dataFrm").serialize();
			 $.post(url,params, function(res){
				layer.msg(res.msg);
				if(res.code==200){
					tableIns.reload();
				}
				layer.close(mainIndex);
			}) 
			return false;
		})
		
		
		//监听菜单和权限选择的按钮事件打开菜单和权限选择的弹出层
		$("#doSelectMenu").click(function(){
			// 父菜单id
			var p_id=$("#p_id").val();
			openMenuSelecter(p_id,function(id,name){
				$("#p_id").val(id);
				$("#p_name").val(name);
			});
		});
    });
</script>
<script>

</script>

</body>
</html>